<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      ref="editRef"
      style="height: 400px; overflow-y: hidden"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
  <el-button
    size="large"
    type="primary"
    style="margin-top: 20px"
    @click="handleBtnClick"
    >发表你的故事</el-button
  >
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, shallowRef } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { useVuexState } from '@/store'
import router from '@/router'
import { IDomEditor } from '@wangeditor/core'

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const editRef = ref<HTMLDivElement | null>()

const mode = 'default'

// 内容 HTML
const valueHtml = ref<string>('')

// 模拟 ajax 异步获取内容
// onMounted(() => {
//   setTimeout(() => {
//     valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
//   }, 1500)
// })

const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
const handleChange = (editor: IDomEditor) => {
  valueHtml.value = editor.getText()
}

const store = useVuexState()
const handleBtnClick = () => {
  store.dispatch('system/createPageDataAction', {
    pageName: 'story',
    newData: {
      title: '造物者',
      content: valueHtml.value
    }
  })
  router.push({ path: '/main/story/list', replace: true })
}
</script>

<style scoped></style>
